from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from .models import UserModel
import random
from django_redis import get_redis_connection

import re
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        token['username'] = str(user.username)
        token['id'] = str(user.id)
        token['avatar'] = str(user.avatar_display)
        return token



class RegisterSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(required=True,write_only=True,max_length=5,min_length=4)

    token = serializers.CharField(read_only=True)
    refresh = serializers.CharField(read_only=True)

    class Meta:
        model = UserModel
        fields = ('phone','password','sms_code','token','refresh')
        extra_kwargs = {
            'password':{
                'write_only':True,
                'required': True,
                'min_length': 6,
                'max_length': 9,
                'error_messages':{
                    'min_length':'密码长度不能小于6位',
                    'max_length':'密码长度不能大于9位',
                    'required':'密码不能为空',
                }
            },
            'phone':{
                'write_only':True,
                'required':True,
                'min_length':11,
                'max_length':11,
                'error_messages':{
                    'min_length':'手机号格式不正确',
                    'max_length':'手机号格式不正确',
                    'required':'手机号不能为空',
                }
            }
        }

    def validate(self, attrs):
        phone = attrs.get('phone',None)
        if not re.match(r'^1[3-9]\d{9}$',phone):
            raise serializers.ValidationError('手机号格式不正确',code='mobile')
        if UserModel.objects.filter(phone=phone).exists():
            raise serializers.ValidationError('手机号已存在',code='mobile')
        sms_code = attrs.get('sms_code',None)
        redis_conn = get_redis_connection('sms_code')
        code = redis_conn.get(f'sms_{phone}')
        if code == None:
            raise serializers.ValidationError('验证码已过期',code='sms_code')
        if code.decode() != sms_code:
            raise serializers.ValidationError('验证码错误',code='sms_code')
        redis_conn.delete(f'sms_{phone}')
        try:
            UserModel.objects.get(phone=phone)
            raise serializers.ValidationError('手机号已存在',code='mobile')
        except UserModel.DoesNotExist:
            print('用户不存在,可以注册')
        attrs.pop('sms_code')
        return attrs

    def create(self, validated_data):
        phone = validated_data.get('phone')
        password = validated_data.get('password')
        username = "用户_" + "{0:05d}".format(random.randint(0,99999))
        user = UserModel.objects.create_user(
            phone=phone,
            password=password,
            username=username,
            avatar="user/default.jpg",
        )
        refresh = CustomTokenObtainPairSerializer.get_token(user)
        user.refresh = str(refresh)
        user.token = str(refresh.access_token)
        return user






